
var createrRole = new Object();
createrRole.roleCode = "creater";
createrRole.roleName = "创建者";
var editorRole = new Object();
editorRole.roleCode = "editor";
editorRole.roleName = "人员";
var viewerRole = new Object();
viewerRole.roleCode = "viewer";
viewerRole.roleName = "观看者";
var adminRole = new Object();
adminRole.roleCode = "admin";
adminRole.roleName = "管理者";
var commenterRole = new Object();
commenterRole.roleCode = "commenter";
commenterRole.roleName = "评论者";
var changeUserId = "";
var selUserAndRole = [];
var defaultRole="";
var sharesavedownloadVal = "";
var	peopleVal = "";
var	inviteVal = "";
var	postsVal = "";
var queryJoinWay ="";
var queryRoleCode ="";
var queryUserName ="";
var pageSize=8;
var queryPageSize=12;//参与人员列表每页显示数
var queryname="";
var count = 0;
var queryCount = 0;
var hash = window.location.hash.slice(1);
var queryGroupId = hash.split(",")[0];
var queryOrgId = hash.split(",")[1];
var windowflag = true;//用于滚动加载
var publicflag = "";//公开邀请

var roleViews =[createrRole,editorRole,viewerRole,adminRole,commenterRole];
$(function(){
	// 通过该方法来为每次弹出的模态框设置最新的zIndex值，从而使最新的modal显示在最前面
    $(document).on('show.bs.modal', '.modal', function (event) {
        var zIndex = 1050 + (10 * $('.modal:visible').length);
        $(this).css('z-index', zIndex);
    });

	$(".uploadBtn").click(function() {
		$("#groupfile").click();
	});
	$('#viewModal').modal('hide');
	$('#viewModal').on('hidden.bs.modal', function () {
		propleList();
	});
	propleList();
	/**
	 * 组设置
	 */
/*	$(".groupImg .glyphicon").click(function(){
		$(".sortList").slideUp(1000);
		$(".groupMenu").slideDown(1000);
		$(".cardOperating .item").parent().each(function(){
			$(this).slideUp(1000);
		});
	});*/
/*	$(".groupMenu .item").click(function(){
		var text = this.innerHTML;
		$(".groupMenu").slideUp(1000);
	});*/
	/**
	 * 筛选--参加方式
	 */
/*	$(".joinWaySort").click(function(){
		$(".joinWayList").slideDown(1000);
		$(".groupMenu").slideUp(1000);
		$(".roleList").slideUp(1000);
		$(".cardOperating .item").parent().each(function(){
			$(this).slideUp(1000);
		});
	});
	$(".joinWayItem .joinWayIco").click(function(){
		$(".joinWayList").slideDown(1000);
		$(".groupMenu").slideUp(1000);
		$(".roleList").slideUp(1000);
		$(".cardOperating .item").parent().each(function(){
			$(this).slideUp(1000);
		});
	});*/
	$(".joinWayList .item").click(function(){
		var text = this.innerHTML;
		queryJoinWay = $(this).attr("value");
		$(".joinWaySort")[0].innerHTML=text;
		propleList();
		/*$(".joinWayList").slideUp(1000);*/
	});
	/**
	 * 筛选--角色
	 */
/*	$(".roleSort").click(function(){
		$(".roleList").slideDown(1000);
		$(".groupMenu").slideUp(1000);
		$(".joinWayList").slideUp(1000);
		$(".cardOperating .item").parent().each(function(){
			$(this).slideUp(1000);
		});
	});
	$(".roleItem .roleIco").click(function(){
		$(".roleList").slideDown(1000);
		$(".groupMenu").slideUp(1000);
		$(".joinWayList").slideUp(1000);
		$(".cardOperating .item").parent().each(function(){
			$(this).slideUp(1000);
		});
	});*/
	$(".roleList .item").click(function(){
		var text = this.innerHTML;
		queryRoleCode = $(this).attr("value");
		$(".roleSort")[0].innerHTML=text;
		propleList();
		/*$(".roleList").slideUp(1000);*/
	});
	

	/*$(document).bind('click',function(){
		$(".cardOperating .item").parent().each(function(){
			$(this).slideUp(1000);
		});
		$(".groupMenu").slideUp(1000);
		$(".sortList").slideUp(1000);
	});*/
/*	$('.sortItem').bind('click',function(e){ 
		stopPropagation(e); 
	});*/
	$(window).scroll(function(){
		var viewH =$(this).height();//可见高度
	    var contentH =$(document).height();//内容高度
	    var scrollTop =$(this).scrollTop();//滚动高度
	    if(scrollTop/(contentH -viewH)>=0.95){ //到达底部100px时,加载新内容
	      // 这里加载数据..
    	  if(windowflag&&queryPageSize<queryCount){
    		  windowflag =false;
    		  queryPageSize+=9;
			  propleList();
		  }
	    }
	})
    
    /**
	 * 滚动条监听事件
	 */
	$(".userList").scroll(function() {
	  var divHeight = $(".userList").height();
	  var ulHeight = $(".userList ul").height();
	  if(divHeight+this.scrollTop>=ulHeight+10){
		  if(pageSize<count){
			  pageSize+=10;
			  selectUserList();
		  }
	  }
	});
});
//列表查询
function propleList() {
	$.get('../../../hivelearn/group/findGroupUserList.json?pageSize='+queryPageSize+'&groupId='+queryGroupId+'&queryGroupId=' + queryGroupId+'&queryJoinWay='+queryJoinWay+'&queryRoleCode='+queryRoleCode+'&queryUserName='+queryUserName, function(datas) {
		if (datas.success) {
			queryCount=datas.data.count;
			for(var i = 0;i<datas.data.resultList.length;i++){
				var d = datas.data.resultList[i];
				if(d.userName.length>12){
					d.uName = d.userName.substring(0,12)+"...";
				}else{
					d.uName = d.userName;
				}
			}
			$(".js-heading-num").text(datas.data.count);
			var dom = _.template($('#topicTpl').html());
			dom = dom(datas.data);
			$("#topic").html(dom);
			windowflag = true;
			isShow();
		}
	})
}
function toShareLearning(){
	window.location.href="../../../hivelearnweb/portal/meetingList/meetingList.html#"+queryOrgId;
};
function updateTopic(id){
	$.get('../../../learn/groupuser/findGroupUser.json?id=' + id+"&groupId="+queryGroupId, function(datas) {
		if (datas.success) {
			
			var dom = _.template($('#viewTpl').html());
			datas.data.roleName="";
			for(var i =0;i<roleViews.length;i++){
				if(roleViews[i].roleCode == datas.data.roleCode){
					datas.data.roleName = roleViews[i].roleName;
				}
			}
			if(!datas.data.headPhoto){
				datas.data.headPhoto="";
			}
			if(!datas.data.isCreater){
				datas.data.isCreater="";
			}
			dom = dom(datas.data);
			$("#view").html(dom);
			isShow();
		}
	})
	$('#viewModal').modal('show');
} 
/*function stopPropagation(e) { 
	if (e.stopPropagation) 
		e.stopPropagation(); 
	else 
		e.cancelBubble = true; 
}*/
//主题页
function meetinglist(){
	window.location.href="../meetingtheme/meetingTheme.html#"+queryGroupId+","+queryOrgId;
}
//活动列表
function activitylist(){
	window.location.href="../activityInfo/activityInfo.html#"+queryGroupId+","+queryOrgId;
}
//修改角色
function updateRole(userId,roleCode){
	changeUserId=userId;
	$("#changeRoleModal").find("[name='selectRole']").each(function(){
		if($(this).val()==roleCode){
			$(this).prop("checked",true);
		}else{
			$(this).prop("checked",false);
		}
	});
	$.ajax({
		url:"../../../hivelearn/group/findAboutGroup.json",
		data:{id:queryGroupId},
		success:function(data){
			$("#changeRoleModal").find(".selectRoleItem").each(function(){
				var cls = $(this).find("div").attr("class");
				for(var i = 0;i<5;i++){
					var d = data.data.roles;
					if(cls=="editor"){
						$(this).find("div").text(changeShow(d.editor));
					}else if(cls=="commenter"){
						$(this).find("div").text(changeShow(d.commenter));
					}else if(cls=="viewer"){
						$(this).find("div").text(changeShow(d.viewer));
					}else if(cls=="admin"){
						$(this).find("div").text(changeShow(d.admin));
					}
				}
			})
		}
	})
	$('#changeRoleModal').modal('show');
}
function changeUserRole(){
	var val = $("#changeRoleModal").find("[name='selectRole']:checked").val();
	$.ajax({
		url:"../../../hivelearn/grouprole/changeUserRole.json",
		data:{"userId":changeUserId,"groupId":queryGroupId,"roleCode":val},
		success:function(data){
			var name ="";
			for(var i =0;i<roleViews.length;i++){
				if(roleViews[i].roleCode == val){
					name = roleViews[i].roleName;
				}
			}
			$('#changeRoleModal').modal('hide');
			var ele = "<button onclick=\"updateRole('"+changeUserId+"','"+val+"')\" class=\"updatePeopleRole peopleRole\">修改</button>";
			$('#viewModal').find(".viewRole").text("组中角色为："+name);
			$("#viewModal").find(".changeRoleBtn").html(ele);
		}
	})
}
//邀请
function inviteUser(item){
	publicflag=item;
	selUserIds = [];
	selUserAndRole = [];
	$("#myModal").find(".selUser").each(function(){
		$(this).remove();
	});
	$("#myModal").find(".selUserGroup").empty();
	var ele="<div class=\"emptyWarn\">首先选择下面的成员</div>";
	$("#myModal").find(".selUserGroup").append(ele);
	selectUserList();
	$('#myModal').modal({backdrop: 'static', keyboard: true});
}
function selectUserList(){
	$.ajax({
		url:"../../../learn/groupuser/findUnSelectUserList.json",
		data:{"pageSize":pageSize,"queryUserName":queryname,"queryGroupId":queryGroupId},
		success:function(data){
			data.data.query.selUsers = selUserIds.join(",");
			for(var i = 0;i<data.data.roles.length;i++){
				var d = data.data.roles[i];
				if(d.isDefaultRole==1){
					defaultRole = d.roleCode;
				}
				if(d.roleCode=="sharesavedownload"){
					sharesavedownloadVal = d.roleScope;
				}else if(d.roleCode=="people"){
					peopleVal = d.roleScope;
				}else if(d.roleCode=="invite"){
					inviteVal = d.roleScope;
				}else if(d.roleCode=="posts"){
					postsVal = d.roleScope;
				}
			}
			if(data.data.query.count){
				count = data.data.query.count;
			}else{
				count = 0;
			}
			var dom = _.template($('#selectUserListTpl').html());
			dom = dom(data.data.query);
			$("#selectUserList").html(dom);
			/**
			 * 选择取消点击事件
			 */
			$('.unSel').click(function(){
				selUser(this);
				$(this).fadeOut(300,function(){
					$(this).next().fadeIn(300);
				});
			});
			$('.sel').click(function(){
				$(this).fadeOut(300,function(){
					$(this).prev().fadeIn(300);
				});
			});
		}
	});
}
//查询人员列表
function searchUserList(){
	queryname = $("#searchUserName").val()?$("#searchUserName").val():"";
	selectUserList();
}
//选中
function selUser(e){
	$("#myModal").find(".emptyWarn").remove();
	var userId = $(e).closest(".itemDiv").find("[name='userId']").val();
	var userImg = $(e).closest(".itemDiv").find(".userImg").prop("outerHTML");
	var userName = $(e).closest(".itemDiv").find(".userName").prop("outerHTML");
	selUserIds.push(userId);
	selUserAndRole.push(userId+","+defaultRole);//默认角色
	var ele = "<div class=\"selUser\">"
			  +"<input type=\"hidden\" name=\"userId\" value=\""+userId+"\"/>"
		      +userImg
		      +userName
		      +" 		<span class=\"delUser glyphicon glyphicon-remove\" onclick=\"delUser(this)\"></span>"
		      +"  	</div>"
	//计数
	$("#myModal").find(".selNum").text(selUserIds.length?"已选中"+selUserIds.length+"人":"");
	$(".selUserGroup").append(ele);
}
//移除
function delUser(e){
	var selUser = $(e).closest(".selUser");
	var userId = $(e).closest(".selUser").find("[name='userId']").val();
	$("#selectUserList").find("[name='userId']").each(function(){
		if($(this).val()==userId){
			$(this).closest(".userItem").find(".sel").click();
		}
	});
	selUser.remove();
	for(var i = 0;i<selUserIds.length;i++){
		if(selUserIds[i]==userId){
			selUserIds.splice(i,1);
			break;
		}
	}
}
//撤销选中
function unSelUser(e){
	var userId = $(e).closest(".userItem").find("[name='userId']").val();
	$(".selUserGroup").find("[name='userId']").each(function(){
		if($(this).val()==userId){
			$(this).closest(".selUser").remove();
		}
	});
	for(var i = 0;i<selUserIds.length;i++){
		if(selUserIds[i]==userId){
			selUserIds.splice(i,1);
			for(var j = 0;j<selUserAndRole.length;j++){
				if(selUserAndRole[j].split(",")[0]==userId){
					selUserAndRole.splice(j, 1);
					break;
				}
			}
			break;
		}
	}
	if(selUserIds.length==0){
		var ele="<div class=\"emptyWarn\">首先选择下面的成员</div>";
		$("#myModal").find(".selUserGroup").append(ele);
	}
	//计数
	$("#myModal").find(".selNum").text(selUserIds.length?"已选中"+selUserIds.length+"人":"");
}

function fNext(){
	if(selUserIds.length>0){
		$.ajax({
			url:"../../../learn/groupuser/findUserList.json",
			data:{"queryUserIds":selUserIds},
			traditional:true,
			success:function(data){
				for(var i = 0;i<data.data.resultList.length;i++){
					for(var j = 0;j<selUserAndRole.length;j++){
						var role = "人员";
						if(selUserAndRole[j].split(",")[1].indexOf("editor")!=-1){
							role = "人员";
						}else if(selUserAndRole[j].split(",")[1].indexOf("commenter")!=-1){
							role = "评论者";
						}else if(selUserAndRole[j].split(",")[1].indexOf("viewer")!=-1){
							role = "观看者";
						}else if(selUserAndRole[j].split(",")[1].indexOf("admin")!=-1){
							role = "管理者";
						}
						if(data.data.resultList[i].userId == selUserAndRole[j].split(",")[0]){
							data.data.resultList[i].roleName = role;
						}
					}
				}
				var dom = _.template($('#userRoleListTpl').html());
				dom = dom(data.data);
				$("#userRoleList").html(dom);
				//单个修改
				$("#userRoleList").find(".selStatus").each(function(){
					$(this).click(function(){
						var username = $(this).closest(".itemDiv").find(".userName").text();
						var selRole = "editor";
						var selUserId = $(this).closest(".itemDiv").find("[name='userId']").val();
						for(var i = 0;i<selUserAndRole.length;i++){
							if(selUserAndRole[i].split(",")[0]==selUserId){
								selRole = selUserAndRole[i].split(",")[1];
								break;
							}
						}
						$("#c_changeUserId").val(selUserId);
						$("#c_changeRoleModal").find(".changeUser").text(username);
						$("#c_changeRoleModal").find("[name='selectRole']").each(function(){
							if(selRole.indexOf($(this).val())!=-1){
								$(this).prop("checked",true);
							}
						});
						$("#c_changeUserId").val(selUserId);
						$("#c_changeRoleModal").find(".changeUser").text(username);
						$("#c_changeRoleModal").modal({backdrop: 'static', keyboard: true});
						c_initRole(sharesavedownloadVal,peopleVal,inviteVal,postsVal);
					});
				})
				$("#groupRoleModal").modal({backdrop: 'static', keyboard: true});
			}
		});
	}else{
		$("#msgModal").find(".msg").text("请选择成员！");
		$("#msgModal").modal("show");
	}
}
//保存单人修改角色
function changeOneUserRole(){
	var changeUserId = $("#c_changeUserId").val();
	var role = $("#c_changeRoleModal").find("[name='selectRole']:checked").val();
	for(var i =0;i<selUserAndRole.length;i++){
		if(selUserAndRole[i].split(",")[0]==changeUserId){
			selUserAndRole[i]=changeUserId+","+role+"#";
		}
	}
	$("#userRoleList").find(".userItem").each(function(){
		var userId = $(this).find("[name='userId']").val();
		if(userId==changeUserId){
			if(role=="editor"){
				$(this).find(".selStatus").text("人员");
			}else if(role=="commenter"){
				$(this).find(".selStatus").text("评论者");
			}else if(role=="viewer"){
				$(this).find(".selStatus").text("观看者");
			}else if(role=="admin"){
				$(this).find(".selStatus").text("管理者");
			}
		}
	});
}
//发出邀请
function sendInvite(){
	if(selUserAndRole&&selUserAndRole.length>0){
		$.ajax({
			url:"../../../hivelearn/group/sendInvite.json",
			traditional:true,
			method:"post",
			data:{"userAndRoles":selUserAndRole,"groupId":queryGroupId,"publicInvite":publicflag},
			success:function(data){
				publicflag="";
				location.reload();
			}
		});
	}
}
//根据姓名查询
function queryUserList(){
	queryUserName = $("#queryUserName").val();
	propleList();
}